/*
 * @(#)RequestData.java 1.0.0 07/11/18 版权所有 2006-2007 LOGI 保留所有权利.
 */
package com.logi.lpromis.tool.request;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.jdesktop.databuffer.DataColumn;
import org.jdesktop.databuffer.DataRow;
import org.jdesktop.databuffer.DataTable;
import org.jdesktop.databuffer.util.ReadDataSetByDOM;
import org.jdesktop.databuffer.util.ReadOrWriteDataSetUtil.XmlReadMode;
import org.jdesktop.databuffer.util.ReadOrWriteDataSetUtil.XmlWriteMode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.logi.lpromis.inter.web.LpromisServletException;
import com.logi.lpromis.log.LogisLog;
import com.logi.lpromis.perm.JdbcTypes;
import com.logi.lpromis.perm.JdbcTypes.DataBaseType;
import com.logi.lpromis.tool.LDataBase;
import com.logi.lpromis.tool.LDataSet;
import com.logi.lpromis.tool.LogisType;
import com.logi.lpromis.tool.LogisType.ServiceCondition;
import com.logi.lpromis.tool.Encrypt.DESEncryptCoder;

/**
 * 类<code>RequestData</code>请求服务类
 * 
 * @author james.mo
 * @version 1.0.0
 */
public class RequestData
{

	/**
	 * MAX_SIZE_SEND = 200MB
	 */
	public static int MAX_SIZE_SEND = 200; // MB

	/**
	 * MAX_SIZE_PER_SEND = 60MB
	 */
	public static int MAX_SIZE_PER_SEND = 60; // MB

	/**
	 * 服务器名
	 */
	public final String C_serverName = "192.168.32.38";

	/**
	 * key 2009-06-10
	 */
	public static String C_secretKey = "";

	/**
	 * 端口号
	 */
	public final int C_portNumber = 6789;

	// 服务器名称
	private String m_serverName = null;

	// 端口号
	private int m_port = 0;

	private LDataSet m_request = null;

	/**
	 * 构造函数
	 */
	public RequestData()
	{
		m_serverName = C_serverName;
		m_port = C_portNumber;

		// eventLog.WriteLog(eventLog.INFO, "begin");
		// 20090610 读取配置文件
		ReadSecreatKeyFromFile();

	}

	public static int GetRequestCount(byte[] buff)
	{
		int count = ((buff[0] & 0xFF) << 24) + ((buff[1] & 0xFF) << 16) + ((buff[2] & 0xFF) << 8) + (buff[3] & 0xFF);
		return count;
	}

	public static byte[] SetRequestCount(int count)
	{
		byte[] buff = new byte[4];
		buff[3] = (byte) (count & 0xFF);
		count >>= 8;
		buff[2] = (byte) (count & 0xFF);
		count >>= 8;
		buff[1] = (byte) (count & 0xFF);
		count >>= 8;
		buff[0] = (byte) count;
		return buff;
	}

	public String LoadRequestForm(InputStream xmlPath)
	{
		String strError = "";
		try
		{
			DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
			domFactory.setValidating(false);
			domFactory.setNamespaceAware(true);
			
			m_request = new LDataSet();
			ReadDataSetByDOM read = new ReadDataSetByDOM(m_request, XmlReadMode.Auto);
			read.DataSetReadXml(domFactory.newDocumentBuilder().parse(xmlPath).getFirstChild());
			
			m_request.clearData();
		}
		catch (Exception e)
		{
			if (m_request != null)
			{
				m_request.clearAll();
				m_request = null;
			}
			strError = e.getLocalizedMessage();
		}
		return strError;
	}

	/**
	 * 装载请求格式数据集
	 * 
	 * @param path
	 *            请求格式文件路径
	 * @return 正确：返回""；错误：返回错误信息
	 */
	public String LoadRequestForm(String xmlPath)
	{
		try
		{
			String strError = "";
			// String xmlPath = BaseDirectory.getBaseDirectory() + path +
			// "/InterfaceFormat/Request.xml";
			// if (m_request != null) {
			// m_request.clearAll();
			// m_request = null;
			// }
			m_request = new LDataSet();
			File f = new File(xmlPath);
			if (!f.exists())
			{
				strError = "文件不存在：" + xmlPath;
				return strError;
			}
			strError = m_request.DataSetReadXml(f, XmlReadMode.Auto);
			return strError;
		}
		catch (Exception e)
		{
			if (m_request != null)
			{
				m_request.clearAll();
				m_request = null;
			}
			return e.getLocalizedMessage();
		}
	}

	public void SetRequestForm(LDataSet request)
	{
		m_request = request;
		return;
	}

	/**
	 * 根据请求类型和参数,产生请求表
	 * 
	 * @param requestType
	 *            请求类型
	 * @param userID
	 *            用户ID
	 * @param password
	 *            口令
	 * @param count
	 *            参数数量
	 * @param paras
	 *            参数数组
	 * @param dtReply
	 *            请求表
	 * @return 错误信息
	 */
	private String SetRequstParamData(int requestType, String userID, String password, int count, String[] paras, LDataSet dtRequest)
	{
		String strError = "";
		try
		{
			if (m_request != null)
			{
				DataTable dataTable1 = dtRequest.AddTable(m_request.getTable(0), true);
				if (dataTable1 == null)
				{
					strError = "创建参数表时出错!";
					return strError;
				}
				if (count > 1)
				{
					for (int i = 1; i < count; i++)
					{
						dataTable1.createColumn(String.class, "Parameter" + (i + 1));
						// aCol.setType(String.class);
					}
				}
				DataRow row = dataTable1.appendRow();
				row.setValue((DataColumn) dataTable1.getColumns().get(0), Integer.toString(requestType));
				row.setValue((DataColumn) dataTable1.getColumns().get(1), "Win_Service");
				row.setValue((DataColumn) dataTable1.getColumns().get(2), "1.00");
				row.setValue((DataColumn) dataTable1.getColumns().get(3), userID);
				row.setValue((DataColumn) dataTable1.getColumns().get(4), password);
				row.setValue((DataColumn) dataTable1.getColumns().get(5), Integer.toString(count));
				if (count > 0)
				{
					for (int i = 0; i < count; i++)
					{
						row.setValue((DataColumn) dataTable1.getColumns().get(6 + i), paras[i]);
					}
				}
				return strError;
			}
			else
			{
				return "没设置请求格式文件！";
			}
		}
		catch (Exception e)
		{
			return e.getLocalizedMessage();
		}
	}

	/**
	 * 增加条件表
	 * 
	 * @param dtRequest
	 *            请求数据集
	 * @param count
	 *            条件数量
	 * @param conds
	 *            条件数组
	 * @return 错误信息
	 */
	private String AddRequstCondition(LDataSet dtRequest, int count, ServiceCondition[] conds)
	{
		String strError = "";
		try
		{
			if (m_request != null)
			{
				DataTable aTable = dtRequest.AddTable(m_request.getTable(1), true);
				if (aTable != null)
				{
					for (int i = 0; i < count; i++)
					{
						DataRow row = aTable.appendRow();
						// 0，条件字段 FieldName 文本
						// 1，条件类型 Type 文本
						// 2，条件值 Value 文本
						// 3，操作符 Relation 文本
						// 4，逻辑关系 Logical 文本
						row.setValue((DataColumn) aTable.getColumns().get(0), conds[i].fieldName);
						row.setValue((DataColumn) aTable.getColumns().get(1), conds[i].fieldType);
						row.setValue((DataColumn) aTable.getColumns().get(2), conds[i].value);
						row.setValue((DataColumn) aTable.getColumns().get(3), conds[i].relation);
						row.setValue((DataColumn) aTable.getColumns().get(4), conds[i].logical);
					}
				}
				else
				{
					strError = "没有条件表！";
				}
				return strError;
			}
			else
			{
				return "没设置请求格式文件！";
			}
		}
		catch (Exception e)
		{
			return e.getLocalizedMessage();
		}
	}

	/**
	 * 增加排序表
	 * 
	 * @param dtRequest
	 *            请求数据集
	 * @param count
	 *            排序域数量*2
	 * @param orders
	 *            排序域和类型数组
	 * @return 错误信息
	 */
	private String AddRequstOrder(LDataSet dtRequest, int count, String[] orders)
	{
		String strError = "";
		try
		{
			if (m_request != null)
			{
				DataTable aTable = dtRequest.AddTable(m_request.getTable(2), true);
				if (aTable != null)
				{
					for (int i = 0; i < count; i += 2)
					{
						DataRow row = aTable.appendRow();
						// 0，排序字段 FieldName 文本
						// 1，排序类型 OrderType 文本
						row.setValue((DataColumn) aTable.getColumns().get(0), orders[i]);
						row.setValue((DataColumn) aTable.getColumns().get(1), orders[i + 1]);
					}
				}
				else
				{
					strError = "没有排序表！";
				}
				return strError;
			}
			else
			{
				return "没设置请求格式文件！";
			}
		}
		catch (Exception e)
		{
			return e.getLocalizedMessage();
		}
	}

	/**
	 * 发送请求数据,获得成功信息(无列表返回的情况)
	 * 
	 * @param request
	 *            请求类型
	 * @param userID
	 *            用户ID
	 * @param password
	 *            口令
	 * @param count
	 *            参数数量
	 * @param paras
	 *            参数数组
	 * @param message
	 *            返回信息
	 * @return 错误信息
	 */
	public String SendRequestData(int request, String userID, String password, int count, String[] paras, String[] message)
	{
		LDataSet dsRequest = new LDataSet("Request");
		String strError = "";
		// 产生请求表
		strError = SetRequstParamData(request, userID, password, count, paras, dsRequest);
		if ("".equals(strError) == false)
		{
			return strError;
		}
		// 转成请求串
		message[0] = dsRequest.DataSetWriteXml(XmlWriteMode.IgnoreSchema);
		// 发送请求,获得回答
		strError = sendRequestGetReply(message[0], message);
		if (!"".equals(strError))
		{
			return strError;
		}
		// 处理返回值
		dsRequest.clearAll();
		strError = dsRequest.DataSetReadXml(message[0], XmlReadMode.Auto);
		if (!"".equals(strError))
		{
			return strError;
		}
		message[0] = "";
		try
		{
			if (dsRequest.getTables().size() > 0)
			{
				DataTable errorTable = dsRequest.getTable(0);
				if (errorTable.getRowCount() > 0)
				{
					if (!"0".equals(errorTable.getRow(0).getValue((DataColumn) errorTable.getColumns().get(0)).toString()))
					{
						strError = errorTable.getRow(0).getValue((DataColumn) errorTable.getColumns().get(1)).toString();
						return strError;
					}
				}
				if (dsRequest.getTables().size() > 1)
				{
					DataTable aTable = dsRequest.getTable(1);
					if (aTable.getRowCount() > 0)
					{
						message[0] = aTable.getRow(0).getValue((DataColumn) aTable.getColumns().get(0)).toString();
					}
				}
			}
			return strError;
		}
		catch (Exception e)
		{
			strError = e.getLocalizedMessage();
			return strError;
		}
	}

	/**
	 * 发送请求数据,获得返回结果数据集
	 * 
	 * @param request
	 *            请求类型
	 * @param userID
	 *            用户ID
	 * @param password
	 *            口令
	 * @param count
	 *            参数数量
	 * @param params
	 *            参数数组
	 * @param conds
	 *            条件数组
	 * @param orders
	 *            分页和排序信息数组
	 * @param dsReply
	 *            返回数据集
	 * @return 错误信息
	 */
	public String SendRequestGetReplyData(int request, String userID, String password, int count, String[] params, ServiceCondition[] conds, String[] orders,
			LDataSet dsReply)
	{
		String strError = "";
		String[] message = new String[1];
		if (dsReply == null)
		{
			strError = "返回数据集不能为null!";
			return strError;
		}
		LDataSet dsRequest = new LDataSet("Request");
		// 产生请求表
		strError = SetRequstParamData(request, userID, password, count, params, dsRequest);
		if (!"".equals(strError))
		{
			return strError;
		}
		// 增加条件表
		if (conds != null)
		{
			if (conds.length > 0)
			{
				strError = AddRequstCondition(dsRequest, conds.length, conds);
				if (!"".equals(strError))
				{
					return strError;
				}
			}
		}
		// 增加排序表
		if (orders != null)
		{
			if (orders.length > 0)
			{
				strError = AddRequstOrder(dsRequest, orders.length, orders);
				if (!"".equals(strError))
				{
					return strError;
				}
			}
		}
		// 转成请求串
		message[0] = dsRequest.DataSetWriteXml(XmlWriteMode.IgnoreSchema);
		// 发送请求,获得回答
		strError = sendRequestGetReply(message[0], message);
		if (!"".equals(strError))
		{
			return strError;
		}
		// 处理返回值
		strError = dsReply.DataSetReadXml(message[0], XmlReadMode.Auto);
		if (!"".equals(strError))
		{
			return strError;
		}
		dsRequest.clearAll();
		return strError;
	}

	/**
	 * 发送请求,获得服务回答数据
	 * 
	 * @param strRequest
	 *            请求字符串
	 * @param strReply
	 *            返回的回答字符串数组
	 * @return 错误信息
	 */
	// jacob.jiang 2010-03-17 修改访问权限
	// private String sendRequestGetReply(String strRequest, String[] strReply)
	public String sendRequestGetReply(String strRequest, String[] strReply)
	{
		String strError = "";
		Socket socket = null;
		InputStream Is = null;
		OutputStream Os = null;
		String strReceive = "";
		try
		{
			// 2008-4-17 byte[] buffer = strRequest.getBytes("Unicode");
			byte[] buffer = strRequest.getBytes(LogisType.getMyUnicodeName()); // "UnicodeLittleUnmarked"

			// encrypt 2009-06-10
			// 2010-08-05 屏蔽可能出现的空指针错误 Sharptooth.Zhang
			if (!"".equals(C_secretKey))
			{
				// 对请求数据进行加密
				buffer = DESEncryptCoder.encryptor(buffer, C_secretKey);
			}

			// byte[] buffLength = SetRequestCount(buffer.length);
			String[] s = m_serverName.split("([0-9]{1,3}\\.){3}[0-9]{1,3}");
			if (s.length == 0)
			{
				InetAddress ip = InetAddress.getByName(m_serverName);
				socket = new Socket(ip, m_port);
			}
			else
			{
				socket = new Socket(m_serverName, m_port);
			}

			// jacob.jiang 2010-04-08 新增 超时设置
			if (m_intSocketRequestTimeOut > 0)
			{
				socket.setSoTimeout(m_intSocketRequestTimeOut);
			}

			Is = socket.getInputStream();
			Os = socket.getOutputStream();
			// ==========================================================================//
			// 分批发送处理
			byte[] buffLength = SetRequestCount(buffer.length);
			Os.write(buffLength, 0, buffLength.length);
			int sendCount = buffer.length;
			int intOffset = 0;
			while (sendCount > 0)
			{
				if (sendCount <= MAX_SIZE_PER_SEND * 1024 * 1024)
				{
					if (sendCount > 10 * 1024 * 1024)
					{
						Os.write(buffer, intOffset, 10 * 1024 * 1024);
						intOffset += (10 * 1024 * 1024);
						sendCount -= (10 * 1024 * 1024);
						Thread.sleep(1);
					}
					else
					{
						Os.write(buffer, intOffset, sendCount);
						sendCount = 0;
					}
				}
				else
				{
					int[] intSendCount =
					{ 0 };
					if (SendData(socket, buffer, intOffset, MAX_SIZE_PER_SEND * 1024 * 1024, intSendCount) == true)
					{
						byte[] cc = new byte[2];
						Is.read(cc, 0, 1);
						intOffset += intSendCount[0];
						sendCount -= intSendCount[0];
					}
					else
					{
						break;
					}
				}
			}
			// ==========================================================================//
			// 分批接收
			buffer = null;
			int[] count = new int[1];
			count[0] = 0;
			int intOffset1 = 0;
			strReceive = GetClientRequestFirst(socket, count);
			if (count[0] == 0)
			{
				strError = "等不到服务返回数据！";
			}
			else
			{
				if (count[0] < MAX_SIZE_SEND * 1024 * 1024)
				{
					buffer = new byte[count[0]];
				}
				else
				{
					strError = "数据大于" + MAX_SIZE_SEND + "M，不处理 ！";
				}
				if ("".equals(strError))
				{
					int received = 0;
					while (count[0] > 0)
					{
						if (count[0] <= MAX_SIZE_PER_SEND * 1024 * 1024)
						{
							received = Is.read(buffer, intOffset1, count[0]);
						}
						else
						{
							int[] received1 =
							{ 0 };
							if (ReceiveData(socket, buffer, intOffset1, MAX_SIZE_PER_SEND * 1024 * 1024, received1) == true)
							{
								byte[] cc =
								{ (byte) 128 };
								Os.write(cc);
								Thread.sleep(10);
							}
							received = received1[0];
						}
						if (received <= 0)
						{
							strError = "Read failed";
							break;
						}
						intOffset1 += received;
						count[0] -= received;
					}
				}
			}

			// decrypt 2009-06-10
			// 2010-08-05 屏蔽可能出现的空指针错误 Sharptooth.Zhang
			if (!"".equals(C_secretKey))
			{
				buffer = DESEncryptCoder.decryptor(buffer, C_secretKey);
				strReceive = new String(buffer, LogisType.getMyUnicodeName());
				strReceive = strReceive.substring(0, strReceive.lastIndexOf(">") + 1);
			}
			else
			{
				strReceive = new String(buffer, 0, intOffset1, LogisType.getMyUnicodeName()); // "UnicodeLittleUnmarked"
			}

			// Is.close();
			// Is=null;
			// Os.close();
			// Os=null;
			socket.close();
			socket = null;
			strReply[0] = strReceive;
			return strError;
		}
		catch (Exception e)
		{
			// 2010-10-15 Lee 标识 客户端错误，以及堆栈信息
			strError = "Client err : " + e.getLocalizedMessage() + " \n";
			return strError + getStackInfo(e);
		}
		finally
		{
			try
			{
				// if(Is!=null)
				// {
				// Is.close();
				// }
				// if(Os!=null)
				// {
				// Os.close();
				// }
				if (socket != null)
				{
					socket.close();
				}
			}
			catch (Exception e)
			{

			}
		}
	}

	private String getStackInfo(Exception e)
	{
		StringBuffer sb = new StringBuffer();
		sb.append(e.getLocalizedMessage() + "\n");
		for (int i = 0; i < e.getStackTrace().length; i++)
		{
			sb.append(e.getStackTrace()[i] + "\n");
		}
		return sb.toString();
	}

	/**
	 * Business Method.
	 */
	public String ReadSecreatKeyFromFile()
	{
		String strError = "";
		InputStream is = null;
		// String[] s = new String[2];
		Element e = null;
		NodeList nodeList = null;
		try
		{
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			is = this.getClass().getClassLoader().getResourceAsStream("/config/format/InterfaceFormat/secretkey.xml");

			if (is != null)
			{
				Document doc = docBuilder.parse(is);

				doc.getDocumentElement().normalize();

				NodeList listOfPersons = doc.getElementsByTagName("LogisSetting");

				for (int s1 = 0; s1 < listOfPersons.getLength(); s1++)
				{
					Node firstPersonNode = listOfPersons.item(s1);
					if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE)
					{
						Element firstElement = (Element) firstPersonNode;

						// SecretKeyWS
						nodeList = firstElement.getElementsByTagName("secretKey");
						e = (Element) nodeList.item(0);
						nodeList = e.getChildNodes();
						C_secretKey = ((Node) nodeList.item(0)).getNodeValue().trim();
					}
				}
			}
			else
			{
				C_secretKey = "";
			}
		}
		catch (SAXParseException err)
		{
			strError = err.getLocalizedMessage();
		}
		catch (SAXException err1)
		{
			strError = err1.toString();
		}
		catch (Throwable t)
		{
			strError = t.toString();
		}
		finally
		{
			is = null;
		}
		return strError;
	}

	/**
	 * 获得通信端口号
	 * 
	 * @return 通信端口号
	 */
	public int getM_port()
	{
		return m_port;
	}

	/**
	 * 设置通信端口号
	 * 
	 * @param m_port
	 *            通信端口号
	 */
	public void setM_port(int m_port)
	{
		this.m_port = m_port;
	}

	/**
	 * 获得服务名
	 * 
	 * @return 服务名
	 */
	public String getM_serverName()
	{
		return m_serverName;
	}

	/**
	 * 设置服务名
	 * 
	 * @param name
	 *            服务名
	 */
	public void setM_serverName(String name)
	{
		m_serverName = name;
	}

	/**
	 * 制作请求数据
	 * 
	 * @param request
	 *            请求类型
	 * @param userID
	 *            用户ID
	 * @param password
	 *            口令
	 * @param count
	 *            参数数量
	 * @param params
	 *            参数数组
	 * @param conds
	 *            条件数组
	 * @param orders
	 *            分页和排序信息数组
	 * @param strReply
	 * @return 错误信息
	 */
	public String MakeRequestGetReplyData(int request, String userID, String password, int count, String[] params, ServiceCondition[] conds, String[] orders,
			String[] strReply)
	{
		String strError = "";
		LDataSet dsRequest = new LDataSet("Request");
		// 产生请求表
		strError = SetRequstParamData(request, userID, password, count, params, dsRequest);
		if (!"".equals(strError))
		{
			return strError;
		}
		// 增加条件表
		if (conds != null)
		{
			if (conds.length > 0)
			{
				strError = AddRequstCondition(dsRequest, conds.length, conds);
				if (!"".equals(strError))
				{
					return strError;
				}
			}
		}
		// 增加排序表
		if (orders != null)
		{
			if (orders.length > 0)
			{
				strError = AddRequstOrder(dsRequest, orders.length, orders);
				if (!"".equals(strError))
				{
					return strError;
				}
			}
		}
		// 转成请求串
		strReply[0] = dsRequest.DataSetWriteXml(XmlWriteMode.IgnoreSchema);
		return strError;
	}

	/**
	 * 获得返回结果数据集
	 * 
	 * @param strReply
	 *            参数数组
	 * @param dsReply
	 *            返回数据集
	 * @return 错误信息
	 */
	public String GetReplyData(String strReply, LDataSet dsReply)
	{
		String strError = "";
		if (dsReply == null)
		{
			strError = "返回数据集不能为null!";
			return strError;
		}
		// 处理返回值
		strError = dsReply.DataSetReadXml(strReply, XmlReadMode.Auto);
		if (!"".equals(strError))
		{
			return strError;
		}
		return strError;
	}

	/**
	 * 获得请求数据
	 * 
	 */
	private String GetClientRequestFirst(Socket clientSocket, int[] count)
	{
		count[0] = 0;
		try
		{
			byte[] buffer = new byte[4];
			int intLength = clientSocket.getInputStream().read(buffer, 0, 4);
			if (intLength == 4)
			{
				count[0] = GetRequestCount(buffer);
			}
			return "";
		}
		catch (Exception ex)
		{
			// ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 接受大数据量数据
	 * 
	 * @param clientSocket
	 * @param buffer
	 * @param intOffset
	 * @param maxRec
	 * @param received
	 * @return
	 */
	private boolean ReceiveData(Socket clientSocket, byte[] buffer, int intOffset, int maxRec, int[] received)
	{
		boolean bFlag = true;
		received[0] = 0;
		try
		{
			int count = maxRec;
			while (count > 0)
			{
				received[0] = clientSocket.getInputStream().read(buffer, intOffset, count);
				if (received[0] <= 0)
				{
					return false;
				}
				intOffset += received[0];
				count -= received[0];
			}
			received[0] = maxRec;
			return bFlag;
		}
		catch (Exception e)
		{
			received[0] = 0;
			bFlag = false;
		}
		return bFlag;
	}

	/**
	 * 发送大数据量数据
	 * 
	 * @author Andygason.chen
	 *
	 * @param clientSocket
	 * @param buffer1
	 * @param intOffset1
	 * @param maxSize
	 * @param intSendCount
	 * @return
	 */
	private boolean SendData(Socket clientSocket, byte[] buffer1, int intOffset1, int maxSize, int[] intSendCount)
	{
		intSendCount[0] = 0;
		int sendCount = maxSize;
		try
		{
			while (sendCount > 0)
			{
				if (sendCount > 10 * 1024 * 1024)
				{
					// stream.Write(buffer1, intOffset1, 10 * 1024 * 1024);
					clientSocket.getOutputStream().write(buffer1, intOffset1, 10 * 1024 * 1024);
					intOffset1 += (10 * 1024 * 1024);
					sendCount -= (10 * 1024 * 1024);
					Thread.sleep(10);
				}
				else
				{
					// stream.Write(buffer1, intOffset1, sendCount);
					clientSocket.getOutputStream().write(buffer1, intOffset1, sendCount);
					sendCount = 0;
				}
			}
			intSendCount[0] = maxSize;
			return true;
		}
		catch (Exception e)
		{
			// TODO: handle exception
			intSendCount[0] = 0;
			return false;
		}
	}

	/**
	 * 发送请求数据,获得返回结果数据集
	 * 
	 * @author justin.yao
	 * @version 2009-11-27
	 * @param request
	 *            请求类型
	 * @param userID
	 *            用户ID
	 * @param password
	 *            口令
	 * @param count
	 *            参数数量
	 * @param params
	 *            参数数组
	 * @param conds
	 *            条件数组
	 * @param orders
	 *            分页和排序信息数组
	 * @param dsReply
	 *            返回数据集
	 * @param proDs
	 *            所要提交的流程数据集
	 * @return 错误信息
	 */
	public String SendRequestGetReplyData(int request, String userID, String password, int count, String[] params, ServiceCondition[] conds, String[] orders,
			LDataSet dsReply, LDataSet proDs)
	{
		String strError = "";
		String[] message = new String[1];
		if (dsReply == null)
		{
			strError = "返回数据集不能为null!";
			return strError;
		}
		LDataSet dsRequest = new LDataSet("Request");
		// 产生请求表
		strError = SetRequstParamData(request, userID, password, count, params, dsRequest);
		if (!"".equals(strError))
		{
			return strError;
		}
		// 增加条件表
		if (conds != null)
		{
			if (conds.length > 0)
			{
				strError = AddRequstCondition(dsRequest, conds.length, conds);
				if (!"".equals(strError))
				{
					return strError;
				}
			}
		}
		// 增加排序表
		if (orders != null)
		{
			if (orders.length > 0)
			{
				strError = AddRequstOrder(dsRequest, orders.length, orders);
				if (!"".equals(strError))
				{
					return strError;
				}
			}
		}

		// 2009-11-27,Justin.Yao,增加流程下各表
		if (proDs != null && proDs.getTables().size() > 0)
		{
			for (int i = 0; i < proDs.getTables().size(); i++)
			{
				DataTable dt = proDs.getTable(i);
				dsRequest.AddTable(dt, false);
			}
		}

		// 转成请求串
		message[0] = dsRequest.DataSetWriteXml(XmlWriteMode.WriteAll);
		// 发送请求,获得回答
		strError = sendRequestGetReply(message[0], message);
		if (!"".equals(strError))
		{
			return strError;
		}
		// 处理返回值
		strError = dsReply.DataSetReadXml(message[0], XmlReadMode.Auto);
		if (!"".equals(strError))
		{
			return strError;
		}
		dsRequest.clearAll();
		return strError;
	}

	/**
	 * 超时时间
	 * 
	 * @author jacob.jiang
	 */
	private static int m_intSocketRequestTimeOut = 0;

	/**
	 * 获取超时时间
	 * 
	 * @author jacob.jiang
	 */
	public static int getSocketRequestTimeOut()
	{
		return m_intSocketRequestTimeOut;
	}

	/**
	 * 获取超时时间
	 * 
	 * @author jacob.jiang
	 */
	public static void setSocketRequestTimeOut(int iTimeOut)
	{
		m_intSocketRequestTimeOut = iTimeOut;
	}

	/**
	 * 将传入的值转为特定数据库可识别的语句 chris.huang 2013-11-6
	 * 
	 * @param value
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public static String convertDateFormat(String value, int DBType) throws LpromisServletException
	{
		try
		{
			StringBuffer sb = new StringBuffer();
			String format = "";
			// 得到格式类型
			if (value.length() < 15)
			{
				SimpleDateFormat shortDateFormat = new SimpleDateFormat("yyyy-MM-dd");
				value = shortDateFormat.format(shortDateFormat.parse(value));
				if (DataBaseType.OracleType == DBType)
				{
					format = "YYYY-MM-DD";
				}
				else if (DataBaseType.MySqlType == DBType)
				{
					format = "%Y-%m-%d";
				}
			}
			else
			{
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				value = dateFormat.format(dateFormat.parse(value));
				if (DataBaseType.OracleType == DBType)
				{
					format = "YYYY-MM-DD HH24:MI:SS";
				}
				else if (DataBaseType.MySqlType == DBType)
				{
					format = "%Y-%m-%d %H:%i:%s";
				}
			}
			// 得到转换出的适用sql
			switch (DBType)
			{
			case DataBaseType.OracleType:
				sb.append(" to_date('" + value + "', '" + format + "') ");
				break;
			case DataBaseType.SqlServerType:
				sb.append(" convert(datetime, '" + value + "', 120) ");
				break;
			case DataBaseType.MySqlType:
				sb.append(" str_to_date('" + value + "', '" + format + "') ");
				break;
			default:
				sb.append("不支持的数据库类型");
				break;
			}
			return sb.toString();
		}
		catch (Exception e)
		{
			throw new LpromisServletException(500, e.getMessage());
		}
	}

	/**
	 * 把条件表转成条件语句 2010-09-04 James 0，条件字段 FieldName 文本 1，条件类型 Type 文本 2，条件值
	 * Value 文本 3，操作符 Operator 文本 4，逻辑关系 Logical 文本
	 * 
	 * @param TBCondition
	 *            条件表
	 * @param strWhere
	 *            输出条件语句
	 * @return 正确：返回""；错误：返回错误信息
	 */
	public static String ConvertCondition(DataTable TBCondition) throws Exception
	{
		StringBuffer filterSB = new StringBuffer(128);
		String strFillChar = "";
		// 初始化（）配对计数
		int intQCount = 0;
		// 重复处理表中每一条记录
		DataColumn dc0 = (DataColumn) TBCondition.getColumns().get(0);
		DataColumn dc1 = (DataColumn) TBCondition.getColumns().get(1);
		DataColumn dc2 = (DataColumn) TBCondition.getColumns().get(2);
		DataColumn dc3 = (DataColumn) TBCondition.getColumns().get(3);
		DataColumn dc4 = (DataColumn) TBCondition.getColumns().get(4);
		for (int i = 0; i < TBCondition.getRowCount(); i++)
		{
			DataRow row = TBCondition.getRow(i);
			String row0 = (row.getValue(dc0) != null) ? row.getValue(dc0).toString().toUpperCase() : "";
			String row1 = (row.getValue(dc1) != null) ? row.getValue(dc1).toString() : "";
			String row2 = (row.getValue(dc2) != null) ? row.getValue(dc2).toString() : "";
			String row3 = (row.getValue(dc3) != null) ? row.getValue(dc3).toString() : "";
			String row4 = (row.getValue(dc4) != null) ? row.getValue(dc4).toString() : "";
			if ("".equals(row0) != true || "".equals(row4) != true)
			{
				// 2011-08-25 Lee 对单独使用And和Or时，拼接问题进行修正
				strFillChar = "";
				if ("(".equals(row4))
				{
					filterSB.append("( ");
					intQCount++;
				}
				else if (")".equals(row4))
				{
					filterSB.append(") ");
					intQCount--;
					if (intQCount < 0)
					{
						throw new Exception("（）不匹配 ！");
					}
				}
				else
				{
					if (!"".equals(row4))
					{
						filterSB.append(" " + row4 + " ");
					}
					filterSB.append(row0 + " " + row3 + " ");
					if ("string".equalsIgnoreCase(row1))
					{
						strFillChar = "'";
					}
					if ("date".equalsIgnoreCase(row1))
					{
						filterSB.append(convertDateFormat(row2, JdbcTypes.LogisDBType));
					}
					else if ("in".equalsIgnoreCase(row3) || "not in".equalsIgnoreCase(row3))
					{
						filterSB.append("(");
						boolean bFirst = true;
						String[] strSplit = row2.split(";");
						for (int j = 0; j < strSplit.length; j++)
						{
							String strItem = strSplit[j];
							if (bFirst)
							{
								bFirst = false;
							}
							else
							{
								filterSB.append(",");
							}
							filterSB.append(strFillChar + strItem + strFillChar);
						}
						filterSB.append(") ");
					}
					else if ("like".equalsIgnoreCase(row3))
					{
						if ("%".equals(row2))
						{
							filterSB.append(strFillChar + "%" + strFillChar);
						}
						else
						{
							filterSB.append(strFillChar + "%" + row2 + "%" + strFillChar);
						}
					}
					else
					{
						filterSB.append(strFillChar + row2 + strFillChar + " ");
					}
				}
			}
		}
		// 最后核实（）配对正确
		if (intQCount != 0)
		{
			throw new Exception("（）不匹配 ！");
		}
		return filterSB.toString();
	}

	/**
	 * 把Order表转成Order串 适合于数据库 0，排序字段 FieldName 文本 1，排序类型 OrderType 文本
	 * 
	 * @param TBOrder
	 *            Order表
	 * @param strOrder
	 *            Order串
	 * @param intPage
	 * @param intPageSize
	 * @return 正确：返回""；错误：返回错误信息
	 */
	public static String ConvertOrder(DataTable TBOrder, int[] pageNumAndSize) throws Exception
	{
		pageNumAndSize[0] = 0;
		pageNumAndSize[1] = 0;
		int dataBaseType = new LDataBase("Logis").GetDataBaseType();

		boolean bFirst = true;
		StringBuffer orderSB = new StringBuffer(128);

		// 串接每一行内容
		DataColumn dc0 = (DataColumn) TBOrder.getColumns().get(0);
		DataColumn dc1 = (DataColumn) TBOrder.getColumns().get(1);
		for (DataRow row : TBOrder.getRows())
		{
			String row0 = (row.getValue(dc0) != null) ? row.getValue(dc0).toString() : "";
			String row1 = (row.getValue(dc1) != null) ? row.getValue(dc1).toString() : "";
			if("".equals(row0) == false)
			{
				if (Character.isDigit(row0.charAt(0)))
				{
					try
					{
						pageNumAndSize[0] = Integer.parseInt(row0);
						pageNumAndSize[1] = Integer.parseInt(row1);
					}
					catch (Exception e)
					{
						pageNumAndSize[0] = 0;
						pageNumAndSize[1] = 0;
					}
				}
				else
				{
					if(bFirst)
					{
						bFirst = false;
					}
					else
					{
						orderSB.append(",");
					}
					if ("TASKNAME".equalsIgnoreCase(row0) || "INITUSER".equalsIgnoreCase(row0))
					{
						// 2013-10-10 Lee 默认ORACLE时，支持拼音排序
						if (dataBaseType == DataBaseType.OracleType)
						{
							orderSB.append("nlssort(" + row0.toUpperCase() + ",'NLS_SORT = SCHINESE_PINYIN_M') " + row1);
						}
						else
						{
							orderSB.append(row0 + " " + row1);
						}
					}
					else
					{
						orderSB.append(row0 + " " + row1);
					}
				}
			}
		}
		return orderSB.toString();
	}
	
	public static String ConvertFilter(String filterJSON)
	{
		if (filterJSON == null || "".equals(filterJSON))
		{
			return "";
		}
		else
		{
			DataTable table = new DataTable();
			try
			{
				table.readJson(filterJSON);

				int intQCount = 0;
				StringBuffer sb = new StringBuffer(128);
				for (DataRow row : table.getRows())
				{
					String relation = LogisType.getObjectString(row.getValue(RequestUtil.FILTER.RELATION));
					String fieldName = LogisType.getObjectString(row.getValue(RequestUtil.FILTER.FIELDNAME));
					String fieldType = LogisType.getObjectString(row.getValue(RequestUtil.FILTER.FIELDTYPE));
					String logical = LogisType.getObjectString(row.getValue(RequestUtil.FILTER.LOGICAL));
					String value = LogisType.getObjectString(row.getValue(RequestUtil.FILTER.VALUE));
					if (!"".equals(fieldName) || !"".equals(relation))
					{
						String strFillChar = "";
						if ("(".equals(relation))
						{
							sb.append("( ");
							intQCount++;
						}
						else if (")".equals(relation))
						{
							sb.append(") ");
							intQCount--;
							if (intQCount < 0)
							{
								throw new LpromisServletException("（）不匹配 ！");
							}
						}
						else
						{
							sb.append(" " + logical + " " + fieldName + " ");
							if (!"".equals(relation))
							{
								sb.append(" " + relation + " ");
							}
							if ("string".equalsIgnoreCase(fieldType))
							{
								strFillChar = "'";
							}
							if ("date".equalsIgnoreCase(fieldType))
							{
								sb.append(convertDateFormat(value, JdbcTypes.LogisDBType));
							}
							else if ("in".equalsIgnoreCase(relation) || "not in".equalsIgnoreCase(relation))
							{
								sb.append("(");
								boolean bFirst = true;
								String[] strSplit = value.split(";");
								for (int j = 0; j < strSplit.length; j++)
								{
									String strItem = strSplit[j];
									if (bFirst)
									{
										bFirst = false;
									}
									else
									{
										sb.append(",");
									}
									sb.append(strFillChar + strItem + strFillChar);
								}
								sb.append(") ");
							}
							else if ("like".equalsIgnoreCase(relation))
							{
								if ("%".equals(value) || "".equals(value) || "*".equals(value))
								{
									sb.append(strFillChar + "%" + strFillChar);
								}
								else
								{
									sb.append(strFillChar + "%" + value + "%" + strFillChar);
								}
							}
							else
							{
								sb.append(strFillChar + value + strFillChar + " ");
							}
						}
					}
				}
				return sb.toString();
			}
			catch (Exception e)
			{
				LogisLog.error(e);
				return "";
			}
		}
	}
	
	public static String[] orderKey =
	{ "TOKENNAME", "TASKNAME","TASKCODE",
        "INITUSER","PROCESSNAME","COMPANY_NAME","RESULT","NAME","POSTNAME" };

	public static boolean checkorderKey(String row0)
	{
		boolean flag = false;
		for (int i = 0; i < orderKey.length; i++)
		{
			if (orderKey[i].equalsIgnoreCase(row0))
			{
				flag = true;
				break;
			}
		}
		return flag;
	}

	public static String ConvertOrder(String[] TBOrder)
	{
		boolean bFirst = true;
		StringBuffer orderSB = new StringBuffer(128);

		int dataBaseType = new LDataBase("Logis").GetDataBaseType();
		// 串接每一行内容
		for (int i = 0; i < TBOrder.length; i += 2)
		{
			String row0 = (TBOrder[i] != null) ? TBOrder[i] : "";
			String row1 = (TBOrder[i + 1] != null) ? TBOrder[i + 1] : "";
			if (!"".equals(row0))
			{
				if (bFirst)
				{
					bFirst = false;
				}
				else
				{
					orderSB.append(",");
				}
				if (checkorderKey(row0))
				{
					// 2013-10-10 Lee 默认ORACLE时，支持拼音排序
					if (dataBaseType == DataBaseType.OracleType)
					{
						orderSB.append("nlssort(" + row0.toUpperCase() + ",'NLS_SORT = SCHINESE_PINYIN_M') " + row1);
					}
					else
					{
						orderSB.append(row0 + " " + row1);
					}
				}
				else
				{
					orderSB.append(row0 + " " + row1);
				}
			}
		}
		return orderSB.toString();
	}
	
	public static String ConvertCondition(ServiceCondition[] TBCondition) throws LpromisServletException
	{
		StringBuffer filterSB = new StringBuffer(128);
		String strFillChar = "";
		// 初始化（）配对计数
		int intQCount = 0;
		for (int i = 0; i < TBCondition.length; i++)
		{
			String row0 = TBCondition[i].fieldName != null ? TBCondition[i].fieldName : "";
			String row1 = TBCondition[i].fieldType != null ? TBCondition[i].fieldType : "";
			String row2 = TBCondition[i].value != null ? TBCondition[i].value : "";
			String row3 = TBCondition[i].relation != null ? TBCondition[i].relation : "";
			String row4 = TBCondition[i].logical != null ? TBCondition[i].logical : "";
			if ("".equals(row0) != true || "".equals(row4) != true)
			{
				// 2011-08-25 Lee 对单独使用And和Or时，拼接问题进行修正
				strFillChar = "";
				if ("(".equals(row4))
				{
					filterSB.append("( ");
					intQCount++;
				}
				else if (")".equals(row4))
				{
					filterSB.append(") ");
					intQCount--;
					if (intQCount < 0)
					{
						throw new LpromisServletException("（）不匹配 ！");
					}
				}
				else
				{
					if (!"".equals(row4))
					{
						filterSB.append(" " + row4 + " ");
					}
					filterSB.append(row0 + " " + row3 + " ");
					if ("string".equalsIgnoreCase(row1))
					{
						strFillChar = "'";
					}
					if ("date".equalsIgnoreCase(row1))
					{
						filterSB.append(convertDateFormat(row2, JdbcTypes.LogisDBType));
					}
					else if ("in".equalsIgnoreCase(row3) || "not in".equalsIgnoreCase(row3))
					{
						filterSB.append("(");
						boolean bFirst = true;
						String[] strSplit = row2.split(";");
						for (int j = 0; j < strSplit.length; j++)
						{
							String strItem = strSplit[j];
							if (bFirst)
							{
								bFirst = false;
							}
							else
							{
								filterSB.append(",");
							}
							filterSB.append(strFillChar + strItem + strFillChar);
						}
						filterSB.append(") ");
					}
					else if ("like".equalsIgnoreCase(row3))
					{
						if ("%".equals(row2))
						{
							filterSB.append(strFillChar + "%" + strFillChar);
						}
						else
						{
							filterSB.append(strFillChar + "%" + row2 + "%" + strFillChar);
						}
					}
					else
					{
						filterSB.append(strFillChar + row2 + strFillChar + " ");
					}
				}
			}
		}
		// 最后核实（）配对正确
		if (intQCount != 0)
		{
			throw new LpromisServletException("（）不匹配 ！");
		}
		return filterSB.toString();
	}
}
